<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="楼栋编码" prop="buildingCode">
        <el-select v-model="queryParams.buildingCode" placeholder="请选择楼栋编码" clearable>
          <el-option
            v-for="dict in buildingCodeDict"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="楼栋名称" prop="buildingName">
        <el-select v-model="queryParams.buildingName" placeholder="请选择楼栋名称" clearable>
          <el-option
            v-for="dict in buildingNameDict"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属区域" prop="region">
        <el-select v-model="queryParams.region" placeholder="请选择所属区域" clearable>
          <el-option
            v-for="dict in dict.type.building_region"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="楼层" prop="floors">
        <el-input
          v-model="queryParams.floors"
          placeholder="请输入楼层"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="房间号" prop="roomNo">
        <el-input
          v-model="queryParams.roomNo"
          placeholder="请输入房间号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="楼栋管理员" prop="userId" label-width="20">
        <el-select v-model="queryParams.userId" placeholder="请选择楼栋管理员" clearable filterable>
          <el-option
            v-for="user in userList"
            :key="user.userId"
            :label="user.userName"
            :value="user.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="管理员联系电话" prop="phonenumber" label-width="20">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入管理员联系电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="楼栋状态" prop="buildStatus">
        <el-select v-model="queryParams.buildStatus" placeholder="请选择楼栋状态" clearable>
          <el-option
            v-for="dict in dict.type.build_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['animalManagement:building:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['animalManagement:building:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['animalManagement:building:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['animalManagement:building:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="buildingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="楼栋编码" align="center" prop="buildingCode">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.building_code" :value="scope.row.buildingCode"/>
        </template>
      </el-table-column>
      <el-table-column label="楼栋名称" align="center" prop="buildingName">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.building_name" :value="scope.row.buildingName"/>
        </template>
      </el-table-column>
      <el-table-column label="所属区域" align="center" prop="region">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.building_region" :value="scope.row.region"/>
        </template>
      </el-table-column>
      <el-table-column label="详细地址" align="center" prop="address" />
      <el-table-column label="楼层" align="center" prop="floors" />
      <el-table-column label="房间号" align="center" prop="roomNo" />
      <el-table-column label="楼栋管理员" align="center" prop="userId">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user" :value="scope.row.userId"/>
        </template>
      </el-table-column>
      <el-table-column label="管理员联系电话" align="center" prop="phonenumber" disabled="true"/>
      <el-table-column label="楼栋状态" align="center" prop="buildStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.build_status" :value="scope.row.buildStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['animalManagement:building:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['animalManagement:building:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改楼栋对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="160px">
        <el-row>
        <el-col :span="12">
            <el-form-item label="楼栋编码" prop="buildingCode">
              <el-select v-model="form.buildingCode" placeholder="请选择楼栋编码" @change="onBuildingCodeChange">
                <el-option
                  v-for="dict in buildingCodeDict"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="楼栋名称" prop="buildingName">
              <el-select v-model="form.buildingName" placeholder="请选择楼栋名称" @change="onBuildingNameChange">
                <el-option
                  v-for="dict in buildingNameDictChange"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
        </el-col>
        </el-row>
        <el-row>
        <el-col :span="12">
            <el-form-item label="所属区域" prop="region">
              <el-select v-model="form.region" placeholder="请选择所属区域">
                <el-option
                  v-for="dict in dict.type.building_region"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="form.address" type="textarea" placeholder="请输入内容" />
            </el-form-item>
        </el-col>
        </el-row>
        <el-row>
        <el-col :span="12">
            <el-form-item label="楼层" prop="floors">
              <el-input v-model="form.floors" placeholder="请输入楼层" />
            </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="房间号" prop="roomNo">
              <el-input v-model="form.roomNo" placeholder="请输入房间号" />
            </el-form-item>
        </el-col>
        </el-row>
        <el-row>
        <el-col :span="12">
            <el-form-item label="楼栋管理员" prop="userId">
              <el-select v-model="form.userId" placeholder="请选择楼栋管理员" filterable @change="onAdminChange">
                <el-option
                  v-for="user in userList"
                  :key="user.userId"
                  :label="user.nickName"
                  :value="user.userId"
                ></el-option>
              </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="管理员联系电话" prop="phonenumber">
              <el-input v-model="form.phonenumber" placeholder="请输入管理员联系电话" />
            </el-form-item>
        </el-col>
        </el-row>
        <el-row>
        <el-col :span="12">
            <el-form-item label="楼栋状态" prop="buildStatus">
              <el-select v-model="form.buildStatus" placeholder="请选择楼栋状态">
                <el-option
                  v-for="dict in dict.type.build_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
        </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBuilding, getBuilding, delBuilding, addBuilding, updateBuilding } from "@/api/animalManagement/building";
import { getUser } from "@/api/animalManagement/cage";
import { getDictsWithSelectOne } from "@/api/system/dict/data";

export default {
  name: "Building",
  dicts: ['building_code', 'building_name', 'building_region', 'build_status', 'sys_user'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 楼栋表格数据
      buildingList: [],
      // 用户列表（楼栋管理员来源于 sys_user）
      userList: [],
      // 楼栋编码字典数据（包含select_one字段）
      buildingCodeDict: [],
      // 楼栋名称字典数据（包含select_one字段）
      buildingNameDict: [],
      buildingNameDictChange: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        buildingCode: null,
        buildingName: null,
        region: null,
        address: null,
        floors: null,
        roomNo: null,
        userId: null,
        phonenumber: null,
        buildStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        buildingCode: [
          { required: true, message: "楼栋编码不能为空", trigger: "change" }
        ],
        buildingName: [
          { required: true, message: "楼栋名称不能为空", trigger: "change" }
        ],
        region: [
          { required: true, message: "所属区域不能为空", trigger: "change" }
        ],
        floors: [
          { required: true, message: "楼层不能为空", trigger: "blur" }
        ],
        roomNo: [
          { required: true, message: "房间号不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getUserList();
    this.getDictsWithSelectOne();

    // 调试：检查字典数据
    this.$nextTick(() => {
      console.log('原始字典数据:', this.dict);
      console.log('building_code:', this.dict.type.building_code);
      console.log('building_name:', this.dict.type.building_name);
    });
  },
  methods: {
    /** 查询楼栋列表 */
    getList() {
      this.loading = true;
      listBuilding(this.queryParams).then(response => {
        this.buildingList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 楼栋编码变更联动楼栋名称
    onBuildingCodeChange(val) {
      console.log('楼栋编码变更:', val);
      console.log('楼栋编码字典:', this.buildingCodeDict);
      console.log('楼栋名称字典:', this.buildingNameDict);
      this.buildingNameDictChange = [];
      // 根据select_one字段查找对应的楼栋名称
      const codeItem = this.buildingCodeDict.find(x => x.dictValue === val);
      if (codeItem) {
        // 在楼栋名称字典中查找对应的项
          this.buildingNameDict.forEach((item, index)=>{
            if(item.selectOne === codeItem.dictValue){
              this.buildingNameDictChange.push(item);
            }
            }
          )
      }
    },
    // 楼栋名称变更联动楼栋编码
    onBuildingNameChange(val) {
      console.log('楼栋名称变更:', val);
      console.log('楼栋编码字典:', this.buildingCodeDict);
      console.log('楼栋名称字典:', this.buildingNameDict);

      // 根据select_one字段查找对应的楼栋编码
      const nameItem = this.buildingNameDict.find(x => x.value === val);
      console.log('找到的名称项:', nameItem);

      if (nameItem && nameItem.selectOne) {
        console.log('名称项的select_one:', nameItem.selectOne);
        // 在楼栋编码字典中查找对应的项
        const codeItem = this.buildingCodeDict.find(x => x.value === nameItem.selectOne);
        console.log('找到的编码项:', codeItem);
        if (codeItem) {
          this.form.buildingCode = codeItem.value;
          console.log('设置楼栋编码:', codeItem.value);
        }
      } else {
        // 如果没有select_one字段，尝试通过label匹配
        if (nameItem) {
          const codeItem = this.buildingCodeDict.find(x => x.label === nameItem.label);
          if (codeItem) {
            this.form.buildingCode = codeItem.value;
            console.log('通过label匹配设置楼栋编码:', codeItem.value);
          }
        }
      }
    },
    /** 获取用户列表（sys_user） */
    getUserList() {
      getUser().then(res => {
        this.userList = res.rows || [];
      });
    },
    /** 获取字典数据（包含select_one字段） */
    getDictsWithSelectOne() {
      // 获取楼栋编码字典数据
      getDictsWithSelectOne('building_code').then(response => {
        console.log('楼栋编码字典数据:', response);
        this.buildingCodeDict = response.data || [];
        // 如果新的API没有数据，回退到原来的字典
        if (this.buildingCodeDict.length === 0) {
          this.buildingCodeDict = this.dict.type.building_code || [];
        }
      }).catch(error => {
        console.error('获取楼栋编码字典失败:', error);
        // 回退到原来的字典
        this.buildingCodeDict = this.dict.type.building_code || [];
      });

      // 获取楼栋名称字典数据
      getDictsWithSelectOne('building_name').then(response => {
        console.log('楼栋名称字典数据:', response);
        this.buildingNameDict = response.data || [];
        // 如果新的API没有数据，回退到原来的字典
        if (this.buildingNameDict.length === 0) {
          this.buildingNameDict = this.dict.type.building_name || [];
        }
      }).catch(error => {
        console.error('获取楼栋名称字典失败:', error);
        // 回退到原来的字典
        this.buildingNameDict = this.dict.type.building_name || [];
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        buildingId: null,
        buildingCode: null,
        buildingName: null,
        region: null,
        address: null,
        floors: null,
        roomNo: null,
        userId: null,
        phonenumber: null,
        buildStatus: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.buildingId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加楼栋";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const buildingId = row.buildingId || this.ids
      getBuilding(buildingId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改楼栋";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.buildingId != null) {
            updateBuilding(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBuilding(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 选择楼栋管理员时，自动带出电话 */
    onAdminChange(val) {
      const u = this.userList.find(x => x.userId === val);
      if (u && u.phonenumber) {
        this.form.phonenumber = u.phonenumber;
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const buildingIds = row.buildingId || this.ids;
      this.$modal.confirm('是否确认删除楼栋编号为"' + buildingIds + '"的数据项？').then(function() {
        return delBuilding(buildingIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('animalManagement/building/export', {
        ...this.queryParams
      }, `building_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
